package cn.wzvtc.demo.service;

import cn.wzvtc.demo.common.constant.CommonStatus;
import cn.wzvtc.demo.common.exception.CommonException;
import cn.wzvtc.demo.model.entity.FormTplEntity;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @description: 模板表单服务类
 * @author: Rex
 * @create: 2021-07-10 19:07
 */
@Service
public class FormTplService {
  @Autowired
  private MongoTemplate mongoTemplate;

  /**
   * 添加数据
   * @param formTplEntity form表单
   */
  public FormTplEntity save(FormTplEntity formTplEntity) {

    //随机生成组件id
    formTplEntity.getComponents().forEach((formTplComponent -> {
      formTplComponent.setId(UUID.randomUUID().toString());
    }));
    return mongoTemplate.insert(formTplEntity);
  }


  /**
   * 根据ID删除整个表单
   * @param id 表单编号
   */
  public void deleteById(String id){
    Query query = Query.query(Criteria.where("id").is(id));
    DeleteResult res = mongoTemplate.remove(query, FormTplEntity.class);
    if (res.getDeletedCount() == 0){
      throw new CommonException(CommonStatus.DELETE_ERROR);
    }
  }

  /**
   * 根据id和component_id删除组件
   * @param id 表单编号
   * @param componentId 组件编号
   */
  public void deleteByIdAndComponentId(String id,String componentId) {
    Update update = new Update();
    update.pull("components",new BasicDBObject("id",componentId));
    Query query = Query.query(Criteria.where("id").is(id));
    UpdateResult res = mongoTemplate.updateFirst(query, update, FormTplEntity.class);
    if (res.getModifiedCount() == 0){
      throw new CommonException(CommonStatus.DELETE_ERROR);
    }
  }


  /**
   * 根据表单模板编号查询表单模板信息
   * @param id 表单编号
   * @return 表单
   */
  public FormTplEntity findById(String id) {
    Query query = new Query(Criteria.where("id").is(id));
    return mongoTemplate.findOne(query, FormTplEntity.class);
  }

  /**
   * 根据id更新数据
   * @param formTplEntity 表单id
   */
  public void update(FormTplEntity formTplEntity) {
    Query query = new Query(Criteria.where("id").is(formTplEntity.getId()));
    Update update = new Update();
    update.set("title", formTplEntity.getTitle());
    update.set("desc", formTplEntity.getDesc());
    update.set("components", formTplEntity.getComponents());
    //更新查询返回的结果集的第一条数据
    mongoTemplate.updateFirst(query, update, FormTplEntity.class);
  }
}
